<template>
	<view class="order-wrap page-bg">
		<view class="address-wrap">
			<view class="addres link" v-if="address.address" @click="link('/pages/mine/addressOrder?op=selectCart')">
				<view class="address-name" >
					<text>{{address.realName}}</text>
					<text>{{address.phoneNumber}}</text>
				</view>
				<view class="address-add desc">{{address.address}}</view>
			</view>
			
			<view class="addres link" v-else @click="link('/pages/mine/addressOrder?op=selectCart')">
				<view class="address-add"  >
					请添加收货地址
				</view>
			</view>
		</view>

		<view class="order-group" v-for="item in userBuyGoods" :key='item.shopId'>
			<view class="order-shop">
				<view class="order-shop-name">{{item.shopName}}</view>
				<view class="order-status status-dfk"></view>
			</view>

			<view class="goods-item" v-for="sub in item.goods" :key='sub.goodsId'>
				<image class="goods-img" :src="sub.goodsImg"></image>
				<view class="goods-info">
					<view class="goods-title">{{sub.goodsName}}</view>
					<view class="goods-sepc">{{sub.goodsSkuName}}</view>
					<view class="goods-price">
						<text class="price yuan">{{sub.goodsSkuPrice | formatMoney}}</text>
						<text class="num-order">x{{sub.goodsNum}}</text>
					</view>
				</view>
			</view>

			<view class="line-info">
				<view class="line-info__title">运费</view>
				<view class="line-info__con">+<text class="yuan"></text>{{totalFreight || 0}}</view>
			</view>
			
			<view class="form-group" v-if="couponList.length > 1">
				<view class="form-group__title">优惠券</view>
				<view class="form-group__con" >
					<picker class="form-group__from tt link" mode="selector" :range="couponList" range-key="option" @change="pickerChange">
						<view class="picker-res">-<text class="yuan"></text>{{selectCoupon.faceValue || 0}}</view>
					</picker>
				</view>
			</view>
			
			<view class="pay-type__item" v-if="disCount.integral > 0" @click="selectDisCountFn(1)">
				<view class="pay-type__type ss" style="padding-left: 0;">{{common.bean}}： {{disCount.integral || 0}}个(最大抵扣{{integralMoneyShow}}元)</view>
				<view class="ins" >
					<view class="ty">豆豆抵扣</view>
					<image class="pay-type__select" v-if="selectDisCount[1]['isSelect']" src="../../static/common/icon_07_on.png" mode=""></image>
					<image class="pay-type__select" v-else src="../../static/common/icon_07.png" mode=""></image>
				</view>
			</view>
			
			<view class="pay-type__item" v-if="disCount.redPacket > 0" @click="selectDisCountFn(2)">
				<view class="pay-type__type ss" style="padding-left: 0;">红包余额：<text class="yuan">{{integralMoneyShow || 0}}</text></view>
				<view class="ins">
					<view class="ty">红包抵扣</view>
					<image class="pay-type__select" v-if="selectDisCount[2]['isSelect']" src="../../static/common/icon_07_on.png" mode=""></image>
					<image class="pay-type__select" v-else src="../../static/common/icon_07.png" mode=""></image>
				</view>
			</view>
			
			<view class="line-info">
				<view class="line-info__title total">小计</view>
				<view class="line-info__con price yuan">{{payMoney | formatMoney}}</view>
			</view>

			<textarea class="message" v-model="message" value="" placeholder="买家留言(选填)" placeholder-class="placeholder" />

			</view>
			
			<view class="pay-type">
				<view class="pay-type__item" @click="selectPayType(2)">
					<image class="pay-type__icon" src="../../static/common/icon_09.png" mode=""></image>
					<view class="pay-type__type">微信支付</view>
					<image class="pay-type__select" v-if="currentPayType===2" src="../../static/common/icon_07_on.png" mode=""></image>
					<image class="pay-type__select" v-else src="../../static/common/icon_07.png" mode=""></image>
				</view>
				<!-- #ifndef H5 -->
				<view class="pay-type__item" @click="selectPayType(3)">
					<image class="pay-type__icon" src="../../static/common/icon_10.png" mode=""></image>
					<view class="pay-type__type">支付宝支付</view>
					<image class="pay-type__select" v-if="currentPayType===3" src="../../static/common/icon_07_on.png" mode=""></image>
					<image class="pay-type__select" v-else src="../../static/common/icon_07.png" mode=""></image>
				</view>
				<!-- #endif -->
				<view class="pay-type__item" @click="selectPayType(1)" >
					<image class="pay-type__icon" src="../../static/common/icon_28.png" mode=""></image>
					<view class="pay-type__type">钱包支付</view>
					<image class="pay-type__select" v-if="currentPayType===1" src="../../static/common/icon_07_on.png" mode=""></image>
					<image class="pay-type__select" v-else src="../../static/common/icon_07.png" mode=""></image>
				</view>
			</view>
				
			<view class="address-center" v-if="address.address">配送至: {{address.address}}</view>
			<view class="address-center" v-else>请选择收货地址</view>
			<view class="once-pay">
				<view class="once-price">
					共<text class="price">{{totalNum}}</text>件商品,应支付: <text class="yuan price">{{payMoney | formatMoney}}</text>
				</view>
				<view class="btn btn-orange" @click="placeOrder">立即付款</view>
			</view>
	<view class="footer-block"></view>
	
	
	</view>
</template>

<script>
	import { api } from '../../utils/api.js'
	import common from '../../utils/common.js'
	export default{
		data() {
			return{
				common,
				currentPayType: 2, // 默认微信支付
				address: {},
				userBuyGoods: {},
				disCount: {
					redPacket: 0, // 红包余额
					integral: 0, // 抵扣豆数量
					integralToAmount: 1, // 豆豆兑换比列
					couponList: [], // 优惠券列表
				}, // 用户折扣信息
				couponList: [],
				selectCoupon: {},
				couponMoney: 0, // 优惠券抵扣价格
				integralMoney: 0, // 抵扣豆装换的钱
				redPacketMoney: 0, // 红包余额
				integralMoneyShow: 0,
				totalFreight: 0, // 总运费, 同一个店铺取最大的
				totalNum: 0,
				totalPrice: 0,
				message: '', // 买家留言
				selectDisCount: [
					{ id: 1, type: 'coupon', isSelect: false },
					{ id: 2, type: 'intagral', isSelect: false },
					{ id: 3, type: 'redPacket', isSelect: false },
				], // 选择的抵扣方式
				cartIdArr: [], // 购物车ID数组
			}
		},
		
		onLoad() {
			let userBuyGoods = common.getStorage('cartInfo') || []
			let cartIdArr = common.getStorage('cartIdArr')
			this.userBuyGoods = userBuyGoods
			this.cartIdArr = cartIdArr
			this.getDiscount()
			this.getAddress()
			this.getTotalFeeight()
		},
		
		methods:{
			// 计算总运费
			getTotalFeeight() {
				let userBuyGoods = this.userBuyGoods 
				let totalFreight = 0
				let totalNum = 0
				let totalPrice = 0
				let temp = []
				userBuyGoods.map(item => {
					// 总运费等于各个店铺中运费最大的一个商品之和
					// 总数量和总价格等于各个店铺的商品数量总和和商品价格总和
					totalNum += item.shopNum
					totalPrice += item.shopPrice
					item.goods.map(sub => {
						temp.push(sub.goodsFreight)
					})
					totalFreight += Math.max(...temp)
				})
				this.totalFreight = totalFreight
				this.totalNum = totalNum
				this.totalPrice = totalPrice
			},
			
			selectPayType(index) {
				this.currentPayType = index
			},
			
			orderPay(url) {
				this.$link(url)
			},
			
			link(url) { this.$link(url) },
			
			getAddress() {
				let that = this
				let address = common.getStorage('userSelectAddress') || {}
				if(Object.keys(address).length > 0){
					that.address = address
				}else{
					api.getAddressListAsync({},(res) => {
						let address = res.items || []
						address.map(item => {
							if(item.isDefault) {
								that.address = item
							}
						})
					}) 
				}
			},
			
			getDiscount() {
				let ShoppingCartIds = this.cartIdArr
			    api.getShoppinCartDiscount( ShoppingCartIds,(res) => {
					 if(Object.keys(res).length){
						 let integralMoney = 0
						 if(res.integralToAmount > 0) {
							 integralMoney = Math.round(res.integral / res.integralToAmount)
						 } 
						 // 格式化优惠券选项
						 let couponList = res.couponList || []
						 if(couponList){
							 res.couponList.map(item => {
								 item.option = `${item.name},减${item.faceValue}元`
							 })
						 }
						 // 优惠券加上不使用选项, 面值为0
						 couponList.push({ name: '不使用', option: '不使用优惠券', faceValue: 0 })
					     this.disCount = res
						 this.couponList =  couponList
						 // 优惠券默认使用
						 this.selectCoupon = res.couponList[0]
						 this.couponMoney = res.couponList[0]['faceValue']
						 this.integralMoneyShow = integralMoney || 0
					 }
				}) 
			},
			
			selectDisCountFn(index) {
				// 设置选中抵扣方式
				let selectDisCount = this.selectDisCount
				selectDisCount[index]['isSelect'] = !selectDisCount[index]['isSelect']
				let isSelect = this.selectDisCount[index]['isSelect']
				if(index === 0) {}
				if(index === 1) {
					// 豆豆
					let integralMoney = 0
					if(this.disCount.integralToAmount > 0) {
						 integralMoney = Math.round(this.disCount.integral / this.disCount.integralToAmount)
					}
					this.integralMoney = isSelect ? integralMoney : 0
				}
				if(index === 2) {
					// 红包
					this.redPacketMoney = isSelect ? this.disCount.redPacket : 0
				}
				this.selectDisCount =  selectDisCount
			},
			
			// 选择优惠券
			pickerChange(e) {
				// 设置优惠券为选中的抵扣方式
				this.selectDisCount[0]['isSelect'] = !this.selectDisCount[0]['isSelect']
				// 设置选中优惠券
				this.selectCoupon = this.couponList[e.detail.value]
				this.couponMoney = this.couponList[e.detail.value]['faceValue']
			},
			
			// 下单接口
			placeOrder() {
				let payType = this.currentPayType
				/* if(this.payMoney === 0) {
					payType = 0
				} */
			
				if(!this.address.id) { this.$showToast('请填写地址信息~'); return }
				let obj = {
					message: this.message,
					shoppingCartIds: this.cartIdArr,
					addressId: this.address.id, // 邮寄地址ID（可选参数）
					points: this.integralNumC, // 积分抵扣量（可选参数）
					redPacket: this.redPacketMoney,
					comSkuId: this.userBuyGoods.goodsSkuId, // 商品规格ID（可选参数）
					payType, // 免费参与：0,钱包支付：1,微信支付:2,支付宝支付:3,全被抵扣(实际支付0):4, 正常情况下，0和4不需要前端传，由后台自行判断，传其他123即可
				}
				api.shoppingCartSettlement(obj,(res) => {
					console.log('下单成功');
					if(!res.payParams) { this.$showToast('支付参数错误, 请稍后重试~'); return }
					let orderInfo = { orderNo: res.orderNo, actualAmount: res.actualAmount } 
					// 缓存信息
					let temp = { ...this.address, ...orderInfo, orderId:res.id, orderPrice: this.payMoney }
					common.setStorage('orderInfo', temp)
					if(res.payParams === 'free') {
						// 免费订单直接跳订单详情
						
						// this.$link('/pages/mine/orderPaySuccess?type=cart')
						uni.showModal({
							title: '商品购买成功',
							content: '',
							confirmText: '查看订单',
							cancelText: '返回首页',
						}).then(res => {
							if(res[1]['confirm']) {
								this.$link('/pages/mine/order')
							}
							if(res[1]['cancel']) {
								this.$link('/')
							}
						})
						
					}else{
						common.uniPay(JSON.parse(res.payParams), orderInfo, () => {
							// this.$link('/pages/mine/orderPaySuccess?type=cart')
							uni.showModal({
								title: '商品购买成功',
								content: '',
								confirmText: '查看订单',
								cancelText: '返回首页',
							}).then(res => {
								if(res[1]['confirm']) {
									this.$link('/pages/mine/order')
								}
								if(res[1]['cancel']) {
									this.$link('/')
								}
							})
						})
					}
				}) 
			}
		},
		
		computed:{
			payMoney: function() {
				let payMoney = this.totalPrice + this.totalFreight - this.couponMoney - this.integralMoney - this.redPacketMoney
				if(payMoney <= 0 ) { payMoney = 0 }
				return payMoney
			},
			
			// 计算豆豆抵扣的数量
			integralNumC: function() {
				let integralNumC = 0
				// 判断用户是否有豆豆
				if(this.disCount.integral > 0) {
					let payMoney = this.payMoney
					// 判读所剩下的钱还需不需要用豆豆抵扣
					if(payMoney > 0 ) {
						// 判断是否选择了豆豆抵扣
						if(this.selectDisCount[1]['isSelect']) {
							integralNumC = payMoney * this.disCount.integralToAmount	
						}
					}
					// 判断是否全部抵扣
					if(integralNumC >= this.disCount.integral) {
						integralNumC = this.disCount.integral
					}
				}
				return integralNumC
			}
		}
	}
</script>

<style scoped lang="less">
	@import url('../../app.less');
	.order-wrap{
		padding: 20upx 30upx;
		box-sizing: border-box;
	}
	.addres{
		background: @f;
		.br;
		.content-20;
		flex-wrap: wrap;
		background: url(../../static/common/icon_08.png) no-repeat left bottom, #fff ;
		background-size: 100% 9upx;
		position: relative;
		margin-bottom: 20upx;
		.address-name{
			.fw;
			.f32;
			width: 100%;
			text{
				padding-right: 20upx;
			}
		}
		
		.address-add{
			.f32;
			padding-bottom: 10rpx;
		}
		.desc{
			padding: 20upx 0;
			.f24;
		}
	}
	.address-wrap{
		.link::after{
			position: absolute;
			right: 20upx;
		}
	}
	.ins{
		flex-grow: 2;
		display: flex;
		justify-content: flex-end;
		align-items: center;
		.ty{
			padding: 0 10rpx;
			box-sizing: border-box;
		}
	}
	.order-group{
		background-color: @f;
		.br;
		.content-20;
		margin-bottom: 20upx;
	}
	.order-group:last-child{
		margin-bottom: 0;
	}
	.order-shop{
		width: 100%;
		margin-bottom: 20upx;
		.flex-base;
		.order-shop-name{
			.flex-base;
			.f24;
			&::before{
				content: '';
				background: url() no-repeat left center;
				background-size: 22upx 22upx;
				display: block;
				width: 22upx;
				height: 24upx;
				padding-right: 10upx;
			}
		}
		
	}
	
	.goods-item{
		.flex-base;
		margin-bottom: 30upx;
		.goods-img{
			width: 150upx;
			height: 150upx;
			.br;
			margin-right: 30upx;
			flex-shrink: 0;
		}
		.goods-info{
			flex-grow: 2;
		}
		.goods-title{
			.f30;
			width: 100%;
		}
		.goods-sepc{
			.f24;
			color: @font-dark-color;
			padding: 10upx 0;
		}
		.goods-price{
			width: 100%;
			.flex-base;
			margin-top: 0;
			justify-content: space-between;
			.num-order{
				.f24;
			}
		}
	
	}
	.line-info{
		.flex-base;
		height: 100upx;
		border-bottom: 1px solid @border-color;
		.total{
			color: @theme-color;
		}
	}
	.message{
		height: 100upx;
		.content-20;
		padding: 20upx 0;
	}

	.pay-type{
		background: @f;
		padding: 0 20upx;
		box-sizing: border-box;
	}
	.pay-type__item{
		width: 100%;
		height: 100upx;
		.flex-base;
		.bb;
	}
	.pay-type__icon{
		width: 38upx;
		height: 38upx;
		flex-shrink: 0;
		object-fit: contain;
	}
	.form-group__con{
		.tt{
			width: 100%;
			justify-content: flex-end;
		}
		
	}
	.form-group{
		.form-group__title{
			.f28;
		}
	}
	
	.pay-type__type{
		.f32;
		flex-grow: 2;
		padding: 0 20upx;
		position: relative;
		}
		.pay-type__item:last-child{
			margin-bottom: none;
		}
	.pay-type__item:nth-of-type(1){
		.pay-type__type{
			&::before{
				content: '';
				    border: 10rpx solid transparent;
				    border-left: none;
				    border-right-color: @theme-color;
				    border-right-width: 10rpx;
				    height: 0;
				    width: 10rpx;
				    box-sizing: border-box;
				    display: block;
					position: absolute;
					left: 160rpx;
					top: 14rpx;
			}
			&::after{
				content: '推荐';
				display: block;
				background-color:@theme-color;
				text-align: center;
				height: 28rpx;
				.f22;
				color: @f;
				width: 60rpx;
				position: absolute;
				    top: 10rpx;
				    left: 168rpx;
				    border-radius: 2px;
			}
			}
	}
	.pay-type__select{
		width: 34upx;
		height: 34upx;
		flex-shrink: 0;
	}
	.address-center{
		.f24;
		color: @theme-color;
		padding: 60upx 0 30upx 0;
	}
	.once-pay{
		height: 100upx;
		.flex-base;
		padding: 0 30upx;
		box-sizing: border-box;
		position: fixed;
		z-index: 99;
		left: 0;
		bottom: 0;
		width: 100%;
		background-color: @f;
	}
	.ss{
		.f28 !important;
	}
</style>
